<?php

declare(strict_types=1);

namespace app\middleware;

use app\service\JwtAuth;

class MiniAuthCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $token = (string) $request->header('Authorization');
        if (empty($token)) {
            return error('token不能为空，请重新登录', [], 401);
        }
        // $token = str_replace('Bearer ', '', $token);

        $ret = JwtAuth::checkToken($token);
        if ($ret['status'] != true) {
            return error($ret['msg'], [], $ret['code']);
        }
        // var_dump($ret);

        $tokenParseInfo = $ret['data'] ?? [];
        $authInfo = (array) $tokenParseInfo['data'] ?? null;

        $request->miniInfo = $authInfo;
        if (!is_null($authInfo)) {
            $request->user_id = $authInfo['user_id'];
            $request->user_type = $authInfo['user_type'];
        }
        return $next($request);
    }
}
